package com.buric.gateway.filter;

import cn.hutool.core.util.ObjectUtil;
import com.buric.common.constant.ContextConstants;
import com.buric.common.constant.MemberKey;
import com.buric.common.constant.TokenConstants;
import com.buric.common.data.R;
import com.buric.common.emun.ResultEnums;
import com.buric.common.sevice.RedisService;
import com.buric.common.utils.ComBeanUtils;
import com.buric.common.utils.JwtUtils;
import com.buric.common.utils.ServletUtils;
import com.buric.gateway.config.IgnoreWhiteProperties;
import io.jsonwebtoken.Claims;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @author: zhou.wei
 * @description 网关鉴权
 * @date: 2024/5/10 10:27
 */

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Resource
    private IgnoreWhiteProperties ignoreWhite;

    @Resource
    private RedisService redisService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();
        // 跳过不需要验证的路径
        if (ignoreWhite.isWhite(url)) {
            return chain.filter(exchange.mutate().request(mutate.build()).build());
        }
        String token = getToken(request);
        if (ObjectUtil.isEmpty(token)) {
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
        }
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) {
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
        }
        boolean isLogin = redisService.hasKey(MemberKey.MEMBER_TOKEN_KEY + ":" + token);
        if (!isLogin) {
            return unauthorizedResponse(exchange, "登录状态已过期");
        }
        String userid = JwtUtils.getUserId(claims);
        String username = JwtUtils.getUserName(claims);
        if (StringUtil.isNullOrEmpty(userid) || StringUtil.isNullOrEmpty(username)) {
            return unauthorizedResponse(exchange, "令牌验证失败");
        }
        addHeader(mutate, ContextConstants.USER_ID, userid);
        addHeader(mutate, ContextConstants.USER_NAME, username);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }


    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlDecode(valueStr);
        mutate.header(name, valueEncode);
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.hasLength(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, "");
        }
        return token;
    }


    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return webFluxResponseWriter(exchange.getResponse(), MediaType.APPLICATION_JSON_VALUE, HttpStatus.OK, msg, ResultEnums.UNAUTHORIZED.getCode());
    }


    public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String contentType, HttpStatus status, Object value, int code) {
        response.setStatusCode(status);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
        R<?> result = R.fail(code, value.toString());
        DataBuffer dataBuffer = response.bufferFactory().wrap(ComBeanUtils.toJson(result).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
